import React from "react";
import { Icon, message, Spin, Popover } from 'antd';
import PersonnelFeeReportService
  from "containers/data-center/report/travel-report/personnel-fee-report/personnel-fee-report.service";
import 'styles/data-center/report/travel-report/fee-report/fee-report.scss';
import Charts from 'components/echarts';
import VscrollCharts from 'components/template/vscroll-echarts/vscroll-echarts';
import SearchArea from 'components/search-area';
import { formatNumber, messages } from "share/common";
import menuRoute from 'routes/menuRoute';
import noDataImg from 'images/no-data.png';
import configureStore from 'stores';
import FRDEService from 'containers/data-center/report/travel-report/personnel-fee-report/data-transfer.service';
import ReportOverview
  from 'containers/data-center/report/travel-report/personnel-fee-report/components/report-overview';
import ExpenseDetail from 'containers/data-center/report/travel-report/personnel-fee-report/components/expense-detail';


class FeeReport extends React.Component {
  constructor(props) {
    super(props);
    this.CTS = [];
    this.baseAmountCache;
    /*
    * CTS 存入被点击的类型数据
    * eg
    * let a = {
    *   type: "departmentExpenseReport",
    *   options: {}
    * }
    * */
    this.state = {
      echartsHeight: 400,
      showSearchArea: true,
      key: 0,
      loading: false,
      searchParams: {},//搜索参数
      searchForm: [],//搜索组件
      isSearching: false,
      allData: {
        expenseTendencyReport: {},
        expenseTypeReport: {},
        statusAmountReport: {},
      },
    }
  }

  componentDidMount() {
    this.InitSearchComponents();
  }

  //初始化搜索组件
  InitSearchComponents = () => {
    PersonnelFeeReportService.InitSearchComponents()
      .then(() => {
        //设置搜索组件
        let searchForm = PersonnelFeeReportService.getFeeReportSearchForm();
        this.setState({
          searchForm
        }, () => {
          this.getAnalysisReport("default")
        })
      })
      .catch(() => {
        this.setState({
          isSearching: false
        })
      })
  }


  /*
  * 顶部数据+其他1-4个报表
  * @params searchParams 查询参数
  * @params triggerType 点击图表的类型
  * */
  getAnalysisReportAction = (searchParams, triggerType, isClickSearch) => {
    let allType = [
      'expenseTendencyReport',
      'expenseTypeReport',
      'statusAmountReport',
    ];
    let getDataType = [];
    let key = this.state.key;
    getDataType = allType.filter(function (item) {
      return item !== triggerType
    });
    this.childUserDetailExpense.refreshComponentLoading();
    PersonnelFeeReportService.getAllDataBySearchParams(searchParams, getDataType, isClickSearch)
      .then(res => {
        let allData = PersonnelFeeReportService.getCanRenderAllDateByApiRes(res, this.CTS);
        if (triggerType) {
          /*
           * 数据不要setState
           * 会导致整个页面组件刷新
           * */
          getDataType.map((type) => {
            this.resetChartOptionByName(type, allData[type][type + "Options"], allData)
          });
          this.childUserDetailExpense.refreshComponent(searchParams);

          // this.setState({
          //   isSearching: false,
          // })
        } else {
          allData = PersonnelFeeReportService.resetStyle(allData);
          key++;
          this.CTS = [];
          this.setState({
            key,
            allData,
            isSearching: false
          }, () => {
            this.childUserDetailExpense.refreshComponent(searchParams)
          })
        }
      })
      .catch(() => {
        this.setState({
          isSearching: false,
        })
      })
  };
  getAnalysisReport = (isDefault, isClickSearch) => {
    let { searchParams } = this.state;
    searchParams.reportId = this.props.params.id;
    if (isDefault) {
      let companyFromFeeReport = configureStore.store.getState().login.company;
      searchParams.filterSetOfBooksId = companyFromFeeReport.setOfBooksId;
      searchParams.filterYear = (new Date()).getFullYear();
      searchParams.filterDateType = "0";
    }
    if ((searchParams.filterYear === "" || !searchParams.filterYear) && isDefault !== "clear") {
      message.warn(messages('data-center.key89')/*请选择年份*/);
      this.setState({
        isSearching: false
      })
      return;
    }
    //趋势报表单独获取
    this.getAnalysisReportAction(searchParams, undefined, isClickSearch);
  }
  //清空搜索
  clearSearchHandle = () => {
    this.setState({
      searchParams: {},
      isSearching: true
    }, () => {
      this.InitSearchComponents();
    })
  }
  //点击搜搜索
  handleSearch = (values) => {
    const { searchParams } = this.state;
    let params = Object.assign(searchParams, values);
    //账套单独处理
    params.filterSetOfBooksId = params.filterSetOfBooksId && params.filterSetOfBooksId.length > 0 ? params.filterSetOfBooksId[0] : "";
    this.setState({
      searchParams: params,
      isSearching: true
    }, () => {
      this.getAnalysisReport(false, true);
    })
  };

  handleSearchAreaEvent = (e, result) => {
    if (e === 'filterDateType') {
      let { filterFormOids, filterStatus } = PersonnelFeeReportService.dataFactory;
      PersonnelFeeReportService.getFilterFormOids(filterFormOids, result);
      PersonnelFeeReportService.getFilterStatus(filterStatus, result);
      if (result === "1") {
        this.formRef.setValues({
          filterFormOids: undefined,
          filterStatus: undefined
        })
      }
      let searchForm = PersonnelFeeReportService.getFeeReportSearchForm();
      this.setState({
        searchForm
      })
    }
  }
  /*
  * 重绘图表
  * 点击哪一个图表，哪一个图表就重绘
  * */
  resetChartOptionByName = (type, option, resAlldata) => {
    let allData = this.state.allData;
    allData[type] = resAlldata[type];
    console.log(type, option)
    switch (type) {
      case 'expenseTendencyReport': {
        this.childExpenseTendencyReport.resetChartOption(option);
        break;
      }
      case 'expenseTypeReport': {
        this.childExpenseTypeReport.resetChartOption(option);
        break;
      }
      case 'statusAmountReport': {
        this.childStatusAmountReport.resetChartOption(option);
        break;
      }
    }
  }
  mergeClickEventLogic = (type, params, chartIndex) => {
    let criteria = null;
    let { allData, searchParams } = this.state;
    let option = allData[type][type + "Options"];
    if (type === "expenseTendencyReport") {
      criteria = parseInt(params.data.month);
    } else {
      criteria = params.data.criteria;
    }
    if (params.color === "#00386b") {
      if (type === "expenseTendencyReport") {
        option.series[0].itemStyle = null;
        searchParams.filterYearMonths = undefined;
        this.baseAmountCache !== undefined && (allData.baseAmount = this.baseAmountCache);
      }
      if (type === "expenseTypeReport") {
        option.series[0].itemStyle = null;
        searchParams.filterExpenseTypeIds = undefined;
      }
      if (type === "statusAmountReport") {
        option.series[0].color = null;
        searchParams.filterStatus = undefined;
      }
      /*
      * this.CTS 是 点击过的 图形报表的队列
      * 再次点击，需要从队列中去掉
      * */
      this.CTS = PersonnelFeeReportService.deleteCTS(this.CTS, type)
    } else {
      if (type === "expenseTendencyReport") {
        option.series[0].itemStyle = FRDEService.getActiveItemStyle(params.dataIndex, option.series[0].data.length);
        searchParams.filterYearMonths = [criteria];
        if (!PersonnelFeeReportService.checkHasCTS(this.CTS, type)) {
          this.baseAmountCache = allData.baseAmount;
        }
        allData.baseAmount = params.data.baseAmount;
      }
      if (type === "expenseTypeReport") {
        option.series[0].itemStyle = FRDEService.getActiveItemStyleByName(params, option);
        searchParams.filterExpenseTypeIds = [criteria]
      }
      if (type === "statusAmountReport") {
        option.series[0].color = FRDEService.getBarOptionsColors(params.dataIndex, option.series[0].data.length);
        searchParams.filterStatus = [criteria]
      }
      this.CTS = PersonnelFeeReportService.addCTS(this.CTS, type, option, params)
    }
    console.log('type', type)
    //其他几个非当前点击报表
    this.getAnalysisReportAction(searchParams, type);
    //当前点击的报表
    this.resetChartOptionByName(type, option, allData);

  }
  //点击费用趋势报表
  clickExpenseTendencyReport = (params) => {
    this.mergeClickEventLogic("expenseTendencyReport", params)
  };
  //点击费用类型报表
  clickExpenseTypeReport = (params) => {
    this.mergeClickEventLogic("expenseTypeReport", params)
  };
  //点击 报销单状态
  clickStatusAmountReport = (params) => {
    this.mergeClickEventLogic("statusAmountReport", params)
  };
  //挂载子组件到当前容器：趋势报表
  onMountExpenseTendencyReport = (expenseTendencyReport) => {
    this.childExpenseTendencyReport = expenseTendencyReport;
  };
  onMountExpenseTypeReport = (expenseTypeReport) => {
    this.childExpenseTypeReport = expenseTypeReport;
  };
  onMountStatusAmountReport = (statusAmountReport) => {
    this.childStatusAmountReport = statusAmountReport;
  };
  onMountUserDetailExpense = (userDetailExpense) => {
    this.childUserDetailExpense = userDetailExpense;
  }
  onMountLoadOverview = (feeReportOverview) => {
    this.childLoadOverview = feeReportOverview;
  }
  renderChartTitle = (type, od) => {
    let _type = type + "Options";
    let title = od[_type] ? od[_type].title._text : "";
    return title

  }
  renderChart = (type, od) => {
    let echartsHeight = this.state.echartsHeight;
    //0.33 宽度；-12 padding； -10 滚动条宽度； -2 浮动
    let width = (document.getElementsByClassName('helios-content')[0].offsetWidth - 40) * 0.50 - 12 - 10 - 2;
    if (od[type] && od[type].length > 0) {
      switch (type) {
        case "expenseTendencyReport": {
          return (
            <Charts
              options={od.expenseTendencyReportOptions}
              height={echartsHeight}
              width="100%"
              clickEcharts={this.clickExpenseTendencyReport}
              onRef={this.onMountExpenseTendencyReport}
              className="echarts-item"/>
          );

          break;
        }
        case "expenseTypeReport": {
          return (
            <VscrollCharts
              options={od.expenseTypeReportOptions}
              height={echartsHeight}
              width={width}
              wrapClassName={'echarts-item-expenseTypeReport'}
              clickEcharts={this.clickExpenseTypeReport}
              onRef={this.onMountExpenseTypeReport}
              className="echarts-item"/>
          );
          break;
        }
        case "statusAmountReport": {
          return (
            <Charts
              options={od.statusAmountReportOptions}
              height={echartsHeight}
              clickEcharts={this.clickStatusAmountReport}
              onRef={this.onMountStatusAmountReport}
              className="echarts-item"/>
          );
          break;
        }
      }
    } else {
      return <div className="no-data-wrap">
        <img src={noDataImg}/>
        <p className="no-data-desc">{messages('data-center.key90')/*暂无数据*/}</p>
      </div>
    }
  }
  //返回到列表
  handleBack = () => {
    let path = menuRoute.getRouteItem('report', 'key').url;
    this.context.router.push(path);
  };

  toggleSearchAreaHandler = () => {
    const { showSearchArea } = this.state;
    this.setState({
      showSearchArea: !showSearchArea
    })
  }

  render() {
    const {
      loading,
      key,
      allData,
      showSearchArea,
      searchForm,
      isSearching
    } = this.state;
    let className, btnClassName, btnContent, iconType;
    if (showSearchArea) {
      className = 'show-sa';
      btnClassName = "show-search-area-btn";
      btnContent = messages('data-center.key115')/*收起搜索区*/;
      iconType = "caret-up";
    } else {
      className = 'hidden-sa';
      btnClassName = "show-search-area-btn-top";
      btnContent = messages('data-center.key114')/*展开收起搜索区*/;
      iconType = "caret-down";
    }
    return (
      <div className="fee-report-setting-wrap personal-report-wrapper">
        <div className='s-wrap personal-search-area-wrap'>
          <div className={className}>
            <SearchArea
              wrappedComponentRef={(inst) => this.formRef = inst}
              searchForm={searchForm}
              clearHandle={this.clearSearchHandle}
              submitHandle={this.handleSearch}
              eventHandle={this.handleSearchAreaEvent}
              loading={isSearching}
            />
          </div>
          <div className='search-area-btn-wrap'>
            <div className={btnClassName} onClick={this.toggleSearchAreaHandler}>
              <Popover content={btnContent}><Icon type={iconType}/></Popover>
            </div>
          </div>
        </div>
        <div className='fee-report-inner-wrap'>
          <div className='echarts-wrap' key={key}>
            {/*key 需要加上，解决 echart 的bug，渲染两层图，导致点击一下，有多次事件触发*/}
            <div className="tendency-report-title-wrap">
              <div className="echarts-title">
                {messages('data-center.key68')/*费用总体趋势报表*/}
                <div className="title-extra-info">
                  <span className="total-amount-span">{messages('data-center.key70')/*总报销金额*/}&nbsp;</span>
                  {allData.baseAmount ? formatNumber(allData.baseAmount) : 0}
                </div>
              </div>
              <div className="tendency-report-wrap">
                <Spin spinning={loading}>
                  {this.renderChart('expenseTendencyReport', allData.expenseTendencyReport)}
                </Spin>
              </div>
            </div>

            <div>
              <div className="echarts-item-title-wrap personnel-echarts-item">
                <div className="echarts-title">
                  {this.renderChartTitle('expenseTypeReport', allData.expenseTypeReport)}
                </div>
                <div className="echarts-item-wrap">
                  <Spin spinning={loading}>
                    {this.renderChart('expenseTypeReport', allData.expenseTypeReport)}
                  </Spin>
                </div>
              </div>

              <div className="echarts-item-title-wrap personnel-echarts-item">
                <div className="echarts-title">{messages('data-center.key128')/*报销单状态占比*/}</div>
                <div className="echarts-item-wrap over-hide">
                  <Spin spinning={loading}>
                    {this.renderChart('statusAmountReport', allData.statusAmountReport)}
                  </Spin>
                </div>
              </div>

              <div className="clear"/>

              <div className="echarts-item-title-wrap echarts-item-user-detail personnel-echarts-item">
                <ExpenseDetail
                  onRef={this.onMountUserDetailExpense}/>
              </div>
              <div className="clear"/>
            </div>
          </div>
        </div>
        <div>
          <a className='back-a' onClick={this.handleBack}>
            <Icon className='back-a-icon' type="rollback"/>
            {messages('common.back')}
          </a>
        </div>
      </div>
    )
  }
}

FeeReport.contextTypes = {
  router: React.PropTypes.object
};
export default FeeReport;
